<template>
    <div class="supply">
            <div class="bigdiv">
                <el-row :gutter="20">
                    <el-col :span="10"  class="singTime">
                        <el-form-item label="签约开始日期" prop="startTime" label-width="120px"
                        :rules="[
                        { required: true, message: '请选择签约开始日期', trigger: 'blur' }
                    ]">
                            <el-date-picker
                                    v-model="supplierSign.startTime"
                                    type="date"
                                    :picker-options="pickerBeginTime"
                                    value-format="yyyy-MM-dd"
                                    placeholder="选择签约开始日期"
                                    >
                            </el-date-picker>
                        </el-form-item>

                    </el-col>

                    <el-col :span="10"  class="singTime">
                        <el-form-item label="签约结束日期" prop="endTime" label-width="120px"
                                 :rules=" [
                                      { required: true, message: '请选择签约结束日期', trigger: 'blur' }
                        ]"  >
                            <el-date-picker
                                    v-model="supplierSign.endTime"
                                    type="date"
                                    :picker-options="pickerEndTime"
                                    value-format="yyyy-MM-dd"
                                    placeholder="选择签约结束日期">
                            </el-date-picker>
                        </el-form-item>

                    </el-col>
                </el-row>

                <br>
                <br>

                <el-row :gutter="20">
                    <el-col :span="10" >

                        <el-form-item label="结算期限"
                                      :rules="[
                        { required: true, message: '请选择结算期限', trigger: 'blur' }]">
                            <template>
                                <el-select v-model="supplierSign.supplierSignDeadline"  placeholder="请选择结算期限" style="width: 300px">
                                    <el-option
                                            v-for="supplierSignDeadline in supplierSignDeadlineList"
                                            :key="supplierSignDeadline.dictCode"
                                            :label="supplierSignDeadline.dictLabel"
                                            :value="supplierSignDeadline.dictLabel"
                                    >
                                    </el-option>
                                </el-select>
                            </template>
                        </el-form-item>

                    </el-col>

                    <el-col :span="10" >
                        <el-form-item label="信用额度/元" prop="creditLimit"  style="width: 350px"
                                      :rules="[
                              { required: true, message: '请填写信用额度', trigger: 'blur' },
                              { type: 'number', message: '必须为数字值',trigger: ['blur', 'change']}
                    ]">
                            <el-input v-model.number="supplierSign.creditLimit" placeholder="请填写信用额度/元"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <br>

                <el-row :gutter="20">
                    <el-col :span="12">


                        <el-form-item label="采购负责人" prop="purchasePerson"
                        >
                            <div class="e1" @click="dialogVisible = true">
                                <span id="person">{{ supplierSign.purchasePerson || '+ 选择成员' }}</span>
                            </div>
                        </el-form-item>

                        <el-dialog
                                title="成员列表"
                                :visible.sync="dialogVisible"
                                :modal="false"
                                width="30%">
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <div>
                                        <el-tree
                                                :data="filtercompanyDepartmentList"
                                                node-key="id"
                                                :props="defaultProps"
                                                :default-expanded-keys="[1]"
                                                @node-click="handleNodeClick">
                                        </el-tree>
                                    </div>
                                </el-col>
                                <el-col :span="12">
                                    <!-- 显示选中部门的领导人信息 -->
                                    <div>
                                        <span>选中部门的员工列表:</span>
                                        <br>
                                        <div id="chooseLeader" v-for="(employee, index) in employeesInDepartment" :key="index">
                                            <span @click="selectEmployee(employee)">{{employee.name}}</span>
                                        </div>
                                    </div>
                                </el-col>
                            </el-row>

                            <span slot="footer" class="dialog-footer">
                                <el-button @click="dialogVisible = false">取 消</el-button>
                                <el-button type="primary" @click="handleConfirm">确 定</el-button>
                            </span>

                        </el-dialog>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="采购归属部门" label-width="120px">
                            <div class="e2">
                                <span id="person2">{{ supplierSign.purchaseDepartment || '选择成员之后自动获取' }}</span>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>


                <br>
                <el-row :gutter="20" style="padding-left: 20px">
                    <el-col :span="10">


                <el-form-item label="合同附件" prop="pic">
                    <el-upload
                            class="upload-demo"
                            :action="$basePath+'manage/imgs/uploadPic?pid=' + supplierSign.supplierId"
                            multiple
                            :before-upload="beforeUpload"
                            :on-success="handleSuccess"
                            accept=".jpg,.jpeg,.png,.webp,.gif"
                            :headers="headers"
                            list-type="picture">
                        <div class="e3">
                            <span id="person3">+ 选择 </span>
                        </div>
                        <div slot="tip" class="el-upload__tip">只能上传.jpg/.jpeg/.png/.webp/.gif文件，且不超过2MB，若不符合要求将无法上传</div>
                    </el-upload>

                </el-form-item>
                    </el-col>
                </el-row>
            </div>
    </div>
</template>

<script>
    import dayjs from 'dayjs';
    export default {
        name: "SupplierSignView",
        data() {
            let _this=this;
            return {
                supplierSign: {
                    supplierId: 1,//供应商id
                    startTime: '',//签约开始日期
                    endTime: '',//签约结束日期
                    supplierSignDeadline: '',//结算期限
                    creditLimit: '',//信用额度
                    purchasePerson: '',//采购负责人(根据部门选择)
                    purchaseDepartment: '',//采购部门
                },
                supplierCode: '',//签约编码
                supplierName: '',//签约名字
                //时间相关设置
                pickerBeginTime:{
                    //date为日历中的每个日期，对开始时间展开的日历中的每个日期都会调用该方法判断是否禁用，返回true表示禁用
                    //禁用大于结束日期的所有的开始日期
                    disabledDate(date){
                        //这里的this为undefined
                      if(_this.supplierSign.startTime!='' &&_this.$dayjs(date).format('YYYY-MM-DD')>=_this.supplierSign.endTime){
                            return true;
                        }
                    }
                },
                pickerEndTime:{
                    //禁用小于开始日期的所有的结束日期
                    disabledDate(date){
                      if(_this.supplierSign.endTime!='' &&_this.$dayjs(date).format('YYYY-MM-DD')<=_this.supplierSign.startTime){
                            return true;
                        }
                    }
                },
                //结算期限相关
                supplierSignDeadlineList:[],
                dialogVisible:false,//点击归属部门弹出对话框
                //树形控件相关--添加仓库主管
                // 存储从后端获取的部门数据相关
                companyDepartmentList:[],//后端传输过来的部门信息
                filtercompanyDepartmentList:[],//过滤完的部门信息
                companyDepartmentName: [], // 存储从后端获取的部门数据
                companyDepartmentId:[],

                employeeList:[],//存储从后端传输过来的所有员工
                employeesInDepartment:[],//存储过滤的(符合所选部门的id下的所有员工)员工们

                defaultProps: {
                    children: 'children',
                    label: 'companyDepartmentName' // 显示部门名称
                },
                brevityCompanyDepartmentId:'',//临时存储数据
                brevityCompanyDepartmentName:'',
                tempSelectedDepartment: '',
                tempSelectedLeader: '',

                //附件上传文件相关
                imageUrl:[],
                headers:{token:window.localStorage.getItem("token")},
            }
        }
        //钩子函数
        ,created() {
            this.getSupplierSignDeadlineList();//从数据库中的字典表中获取结算期限
            this.getCompanyDepartment();//查询所有部门
            this.getEmployeeList();//查询所有员工

        },
        watch: {
            supplierSign: {
                handler(newVal) {
                    this.updateData();
                },
                deep: true
            }
        }
        //方法
        ,methods:{
            resetData() {
                this.supplierSign = {
                    supplierId: '', // 供应商id
                    startTime: '', // 签约开始日期
                    endTime: '', // 签约结束日期
                    supplierSignDeadline: '', // 结算期限
                    creditLimit: '', // 信用额度
                    purchasePerson: '', // 采购负责人(根据部门选择)
                    purchaseDepartment: '', // 采购部门
                };
                this.imageUrl=[];
                this.dialogVisible = false; // 关闭成员选择对话框
                this.brevityCompanyDepartmentId = ''; // 重置临时存储的部门ID
                this.brevityCompanyDepartmentName = ''; // 重置临时存储的部门名称
                this.tempSelectedDepartment = ''; // 重置临时存储的部门
                this.tempSelectedLeader = ''; // 重置临时存储的员工
            },
            updateData() {
                this.$emit('update:supplierData', {
                    startTime: this.supplierSign.startTime,
                    endTime: this.supplierSign.endTime,
                    settlementPeriod: this.supplierSign.supplierSignDeadline,
                    creditLimit: this.supplierSign.creditLimit,
                    purchasePerson: this.supplierSign.purchasePerson,
                    purchaseDepartment: this.supplierSign.purchaseDepartment
                });
            },
            //查询所有员工
            getEmployeeList(){
                this.$axios.get("manage/employee/list").then(
                    response=>{
                        this.employeeList=response.data.data;
                    });
            },
            //从数据库中的字典表中获取结算期限
            getSupplierSignDeadlineList(){
                this.$axios.get("manage/scmDictData/dictDataList",{
                    params: { dataType: 'supplier_sign_deadline' }
                }).then(
                    response=>{
                        this.supplierSignDeadlineList=response.data.dataType;
                    })
                    .catch(error => {
                        console.error("获取结算期限数据失败：", error);
                        alert("获取失败,请刷新重试")
                    });
            },
            //查询所有部门
            getCompanyDepartment() {
                this.$axios.get("manage/companyDepartment/list")
                    .then(response => {
                        this.companyDepartmentList = response.data.data;
                        // 进行数据过滤
                        this.filtercompanyDepartmentList = this.companyDepartmentList.map(item => {
                            return {
                                companyDepartmentId:item.id,
                                companyDepartmentName:item.name,
                                children: []
                            };
                        });
                    })
            },
            //树形控件相关--添加部门
            // 处理节点点击事件(参数是点击的节点的名称)
            handleNodeClick(companyDepartmentName) {
                if (companyDepartmentName && companyDepartmentName.companyDepartmentId) {
                    //检查 companyDepartmentName 是否存在并且其具有 companyDepartmentId 属性

                    this.brevityCompanyDepartmentId = companyDepartmentName.companyDepartmentId;
                    //把点击的部门的id放到一个临时的地方
                    this.brevityCompanyDepartmentName = companyDepartmentName.companyDepartmentName;
                    //把点击的部门的名字放到一个临时的地方

                    // 调用获取该部门下面所有员工的方法通过部门的id来找
                    this.getEmployeesByDepartmentId(companyDepartmentName.companyDepartmentId);
                }
            },
            // 过滤出属于该部门的员工列表,过滤完放到一个位置中去
            getEmployeesByDepartmentId(companyDepartmentId) {
                this.employeesInDepartment = this.employeeList.filter(employee => employee.companyDepartmentId === companyDepartmentId);
            },
            //存放点击的员工
            selectEmployee(employee) {
                this.tempSelectedLeader = employee.name;
            },
            // 点击确定按钮的处理函数
            handleConfirm() {
                if (!this.brevityCompanyDepartmentId) {
                    alert('请选择一个部门');
                    return;
                }
                const selectedNode = this.companyDepartmentName.find(node => node.companyDepartmentId === this.brevityCompanyDepartmentId);
                if (!this.tempSelectedLeader) {
                    alert('请选择员工');
                    return;
                }
                else {
                    this.dialogVisible = false;
                }

                //给supplierSign中的两条属性赋值
                this.supplierSign.purchasePerson = this.tempSelectedLeader;
                this.supplierSign.purchaseDepartment = this.brevityCompanyDepartmentName;
                // 取消验证提示
                this.dialogVisible = false;
            },
            //附件上传相关事件
            //禁用掉删除功能

            //图片上传之前的验证，返回true就会执行上传，返回false不执行上传
            beforeUpload(file) {
                const allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
                const isAllowedType = allowedTypes.includes(file.type);
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isAllowedType) {
                    this.$message.error('上传的图片只能是.jpg,.jpeg,.png,.webp 或.gif 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isAllowedType && isLt2M;
            },
            //文件上传成功所调用的方法
            handleSuccess(res, file) {
                if (res.code == 10005) {
                    this.$message.error('上传图片大小超过!');
                    return;
                }
                this.imageUrl.push({
                    url: this.$basePath + "static/uploadImage/" + res.fileName,
                    imges: res.fileName,
                    type: '合同附件',
                    enable: true,
                    remark: ''
                });
                this.$emit('update:imageUrl', this.imageUrl);
            },
        }


    }
</script>

<style scoped>
    .el-form-item {
        display: flex;
        align-items: center; /* 垂直居中对齐 */
    }

    .el-form-item label {
        margin-right: 10px; /* 标签和输入框之间的间距 */
    }
    .singTime{
        margin-top: 15px;
    }
    .e1 {
        padding: 0;
        border: 1px dashed #666;
        width: 350px;
        border-radius: 2px;
        text-align: center;
        cursor: pointer;
        font-weight:lighter;
    }
    .e2 {
        padding: 0;
        border: 1px dashed #666;
        width: 350px;
        border-radius: 2px;
        text-align: center;
        cursor: pointer;
        font-weight:lighter;
    }
    .e3{
        border: 1px dashed #666;
        width: 350px;
        border-radius: 2px;
        text-align: center;
        cursor: pointer;
        font-weight:lighter;
    }
    #chooseLeader{
        cursor: pointer;
    }
    .titleStr {
        line-height: 30px;
        color: #409EFF;
    }
    .describe {
        font-size: 14px;
        color: #666;
    }
    .demonstration{
        padding-left: 20px;
        font-size: 14px;
        color: #666;
    }
</style>